package org.cloudie.docs.editor.client.widgets;

import org.cloudie.docs.editor.client.extended.FileDropEvent;
import org.cloudie.docs.editor.client.extended.FileDropHandler;
import org.cloudie.docs.editor.client.extended.HasFileDropHandlers;
import org.cloudie.docs.editor.client.extended.FileDropEvent.FileDropNativeEvent;

import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ContextMenuEvent;
import com.google.gwt.event.dom.client.ContextMenuHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.dom.client.HasContextMenuHandlers;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.AbsolutePanel;

public class AdvancedPanel extends AbsolutePanel
    implements HasClickHandlers, HasContextMenuHandlers,
        HasFileDropHandlers{

  private HandlerManager manager;
	  
  public AdvancedPanel() {
    manager = new HandlerManager(this);
    sinkEvents(Event.ONCLICK | Event.ONCONTEXTMENU);
    setupListeners(this, this.getElement());
  }
	
  @Override
  public void fireEvent(GwtEvent<?> event) {
    manager.fireEvent(event);
  }
	
  @Override
  public void onBrowserEvent(Event event) {
    if (event.getTypeInt() == Event.ONCLICK) {
      ClickEvent.fireNativeEvent(event, this);
    } else if (event.getTypeInt() == Event.ONCONTEXTMENU) {
      event.stopPropagation();
      event.preventDefault();
      ContextMenuEvent.fireNativeEvent(event, this);
    }
    super.onBrowserEvent(event);
  }
  
  @Override
  public HandlerRegistration addClickHandler(ClickHandler handler) {
    return manager.addHandler(ClickEvent.getType(), handler);
  }

  @Override
  public HandlerRegistration addContextMenuHandler(
      ContextMenuHandler handler) {
    return manager.addHandler(ContextMenuEvent.getType(), handler);
  }
  
  public void onFileDrop(FileDropNativeEvent event) {
	FileDropEvent.fire(this, event);
  }

  @Override
  public HandlerRegistration addFileDropHandler(FileDropHandler handler) {
	return manager.addHandler(FileDropEvent.getType(), handler);
  }
  
  private native void setupListeners(AdvancedPanel dp, Element el) /*-{
    if (el.addEventListener) {
      el.addEventListener("dragenter", function(e){ e.preventDefault(); e.stopPropagation(); }, false);
      el.addEventListener("dragleave", function(e){ e.preventDefault(); e.stopPropagation(); }, false);
      el.addEventListener("dragover", function(e){ e.preventDefault(); e.stopPropagation(); }, false);
	  el.addEventListener("drop", function(e){
	    dp.@org.cloudie.docs.editor.client.widgets.AdvancedPanel::onFileDrop(Lorg/cloudie/docs/editor/client/extended/FileDropEvent$FileDropNativeEvent;)(e);
	  }, false);
    }
  }-*/;

}
